import axios from 'axios'
import type { AxiosResponse, AxiosRequestConfig } from 'axios'
import { message } from 'ant-design-vue'

const api = axios.create({
  baseURL: '/api',
})

api.interceptors.request.use(
  (config) => {
    // 添加 token 到请求头
    const token = localStorage.getItem('token')
    console.log('token', token)
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)

api.interceptors.response.use(
  (response: AxiosResponse) => {
    if (response) {
      if (response.data.code === 0) {
        return response.data
      }
      if (response.data.code === 401) {
        message.error('未登录或登录已过期，请重新登录')
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
        window.location.replace('/login')
        return Promise.reject('未登录或登录已过期，请重新登录')
      } else {
        message.error(response.data.msg || '请求失败，请稍后再试')
        return Promise.reject(response.data.msg || '请求失败，请稍后再试')
      }
    } else {
      return Promise.reject('请求失败，请稍后再试')
    }
  },
  (err) => {
    return Promise.reject(err)
  },
)

export default {
  get: <T = any>(url: string, args?: AxiosRequestConfig): Promise<ApiResponse<T>> =>
    api.get(url, { ...args }),
  post: <T = any>(url: string, data?: any, args?: AxiosRequestConfig): Promise<ApiResponse<T>> =>
    api.post(url, data, { ...args }),
}
